/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @param {number} left
 * @param {number} right
 * @return {ListNode}
 */
// 翻转链表，就是头插法建表
var reverseBetween = function (head, left, right) {
    if (left === right) return head
    let ptr = head
    let count = 1
    let dummy = new ListNode()
    let temp = dummy
    let pre = null, tail = null, flag = false
    while (ptr) {
        // 不需要翻转 直接接上
        if (count < left) {
            temp.next = ptr
            temp = temp.next
            ptr = ptr.next
        } else if (count >= left && count <= right) { // 进行翻转
            if (count === left) tail = ptr
            let ptr2 = ptr.next
            ptr.next = pre
            pre = ptr
            ptr = ptr2
        } else { // 不需要翻转
            if (count === right + 1) {  // 第一个直接街上
                temp.next = pre
                temp = tail
                flag = true // 是否接上过？
            }
            temp.next = ptr
            temp = temp.next
            ptr = ptr.next
        }
        count++
    }
    // 没有接上过（right是最后一个节点）
    if (!flag) {
        temp.next = pre
        temp = tail
    }
    return dummy.next ? dummy.next : pre
};